<template>
	<a
		v-if="to"
		:href="linkUrl"
		:target="target"
		:class="classes"
		@click.exact="handleClickItem($event, false)"
		@click.ctrl="handleClickItem($event, true)"
		@click.meta="handleClickItem($event, true)"
		:style="itemStyle"
	>
		<slot></slot>
	</a>
	<li v-else :class="classes" @click.stop="handleClickItem" :style="itemStyle">
		<slot></slot>
	</li>
</template>

<script lang="ts">
	import Anes from "../base";
	import { Prop, Component } from "vue-property-decorator";
	import { findComponentsUpward, findComponentUpward } from "../../utils/assist";

	import Menu from "./menu.vue";
	import { submenu, menu } from ".";

	const prefixCls = "ivu-menu";
	@Component
	export default class MenuItem extends Anes {
		@Prop({ type: [String, Number], required: true })
		name!: string | number;

		@Prop({ type: Boolean, default: false })
		disabled!: boolean;

		active = false;

		get classes() {
			return [
				`${prefixCls}-item`,
				{
					[`${prefixCls}-item-active`]: this.active,
					[`${prefixCls}-item-selected`]: this.active,
					[`${prefixCls}-item-disabled`]: this.disabled
				}
			];
		}
		get itemStyle() {
			if (this.hasParentSubmenu && this.parentmenu?.mode !== "horizontal") {
				return {
					paddingLeft: 43 + (this.parentSubmenuNum - 1) * 24 + "px"
				};
			} else {
				return {};
			}
		}

		get hasParentSubmenu() {
			return this.parentSubmenuNum > 0;
		}
		get parentSubmenuNum() {
			return findComponentsUpward(this, "Submenu").length;
		}
		get parentmenu() {
			return findComponentUpward<Menu>(this, "Menu");
		}

		handleClickItem(event: Event, newWindow = false) {
			if (this.disabled) return;

			if (newWindow || this.target === "_blank") {
				// 如果是 new_window，直接新开窗口就行，无需发送状态
				this.handleCheckClick(event, newWindow);
				const parentMenu = findComponentsUpward(this, "Menu");
				if (parentMenu) (parentMenu as any).handleEmitSelectEvent(this.name);
			} else {
				const parent = findComponentsUpward(this, "Submenu");

				if (parent) {
					this.dispatch<submenu>("on-menu-item-select", this.name);
				} else {
					this.dispatch<menu>("on-menu-item-select", this.name);
				}

				this.handleCheckClick(event, newWindow);
			}
		}
	}
</script>

<style>
</style>